package com.ailot.cloud.auth.config;


import com.ailot.cloud.auth.handler.JwtAuthenticationFailureHandler;
import com.ailot.cloud.auth.handler.JwtAuthenticationSuccessHandler;
import com.ailot.cloud.auth.service.JwtUserDetailsService;
import com.ailot.cloud.base.security.authentication.JwtAuthenticationProvider;
import com.ailot.cloud.base.security.authentication.filter.JwtAuthenticationFilter;
import com.ailot.cloud.base.security.authentication.filter.JwtAuthenticationTokenFilter;
import com.ailot.cloud.base.security.authentication.handler.JwtAccessDeniedHandler;
import com.ailot.cloud.base.security.authentication.handler.JwtLogoutSuccessHandler;
import com.ailot.cloud.base.security.config.PermitUrlProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfigurer {

    private final JwtUserDetailsService jwtUserDetailsService;
    private final JwtAuthenticationSuccessHandler jwtAuthenticationSuccessHandle;
    private final JwtAuthenticationFailureHandler jwtAuthenticationFailureHandler;

    private final PermitUrlProperties permitUrlProperties;

    public SpringSecurityConfigurer(JwtUserDetailsService jwtUserDetailsService, JwtAuthenticationSuccessHandler jwtAuthenticationSuccessHandle, JwtAuthenticationFailureHandler jwtAuthenticationFailureHandler, PermitUrlProperties permitUrlProperties) {
        this.jwtUserDetailsService = jwtUserDetailsService;
        this.jwtAuthenticationSuccessHandle = jwtAuthenticationSuccessHandle;
        this.jwtAuthenticationFailureHandler = jwtAuthenticationFailureHandler;
        this.permitUrlProperties = permitUrlProperties;
    }

    /**
     * Configuration using lambdas
     *
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    @Primary
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
        permitUrlProperties.getUrls()
                .forEach(url -> registry.antMatchers(url).permitAll());
        registry.anyRequest().authenticated();
        http
                //禁用表单登录
                .formLogin().disable()
                // 关闭csrf
                .csrf((csrf) -> csrf.disable())
                //禁用session，JWT校验不需要session
                .sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .exceptionHandling((execption) -> execption
                        // 未授权异常处理
                        .accessDeniedHandler(new JwtAccessDeniedHandler()))
                //登出成功处理
                .logout().logoutSuccessHandler(new JwtLogoutSuccessHandler());
        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        http.addFilterAfter(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    JwtAuthenticationFilter jwtAuthenticationFilter() {
        JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter();
        jwtAuthenticationFilter.setAuthenticationManager(authenticationManager());
        jwtAuthenticationFilter.setAuthenticationSuccessHandler(jwtAuthenticationSuccessHandle);
        jwtAuthenticationFilter.setAuthenticationFailureHandler(jwtAuthenticationFailureHandler);
        return jwtAuthenticationFilter;
    }

    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter(permitUrlProperties);
    }

    JwtAuthenticationProvider jwtAuthenticationProvider() {
        JwtAuthenticationProvider jwtAuthenticationProvider = new JwtAuthenticationProvider();
        //设置userDetailsService
        jwtAuthenticationProvider.setUserDetailsService(jwtUserDetailsService);
        //设置加密算法
        jwtAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return jwtAuthenticationProvider;
    }

    /**
     * 自定义的认证处理器
     */
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(jwtAuthenticationProvider());
    }

    /**
     * 指定加解密算法
     *
     * @return
     */
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
